﻿
@using Treca.Business.Base_SysManage;
@using Treca.PushMessage.Entity;
@using Treca.Base_SysManage.Entity;
@using Treca.Util;
@using EFCore.Sharding;
@inherits DependencyViewPage 
@using System.Data;
@using Microsoft.AspNetCore.Http;
@using Newtonsoft.Json;
@{
    Layout = "~/Views/Shared/_Layout_NewMainList.cshtml";
    PermissionManage PermissionManage = new PermissionManage();

    DataTable obj = Model;
    var guid = ViewData["guid"];
    var key = ViewData["key"];
    var value = ViewData["value"];
    var TableName="ms_messageuser";
    Boolean isview = (Boolean)this.ViewData["isview"];
    var objStr = Html.Raw(JsonConvert.SerializeObject(obj));
    BaseDataHelper dataHelper = (BaseDataHelper)this.ViewData["listHelper"];
  //按钮权限
    var manageSysPermission = PermissionManage.OperatorHasPermissionValue("ms_messageuser.manageSysPermission"); //权限权限分配
    var canManage = PermissionManage.OperatorHasPermissionValue("ms_messageuser.manage");//管理
    var canadd = PermissionManage.OperatorHasPermissionValue("ms_messageuser.add");//添加
    var canOCRinput = PermissionManage.OperatorHasPermissionValue("ms_messageuser.OCRinput");//ocr识别
    var candelete = PermissionManage.OperatorHasPermissionValue("ms_messageuser.delete");//删除
    var canmodify = PermissionManage.OperatorHasPermissionValue("ms_messageuser.modify");//修改
    var canapprove = PermissionManage.OperatorHasPermissionValue("ms_messageuser.approve");//审核
    var canReverse = PermissionManage.OperatorHasPermissionValue("ms_messageuser.Reverse");//反审核

    //字段级权限
    var candata = PermissionManage.OperatorHasPermissionValue("ms_messageuser.data");//数据权限
    var canprice = PermissionManage.OperatorHasPermissionValue("ms_messageuser.price");//价格权限

    //记录级权限,有记录级权限，初始化表格GetDataList返回全部数据，没有记录级权限只返回用户自己建立的数据/或者部门建立的数据
    var canRecord = PermissionManage.OperatorHasPermissionValue("ms_messageuser.Record");//记录级权限
    var canDepartment = PermissionManage.OperatorHasPermissionValue("ms_messageuser.deptRecord");//部门记录级权限
   }
<div class="fx-content">
      <div id = "toobar" >   
           <div class="btn-group btn-group-sm">
               <form class="form-inline" id="searchForm">
                    <div class="form-group">
                    @if (canManage&&!isview)
                    {
                        <button onclick = "openForm('', '@TranslateService.GetTranslate("", "System_Add", "添加")'); " type = "button" class="btn btn-success" aria-label="Left Align">
                            <span class="iconfont icon-ysic_add" aria-hidden="true"></span>
                        @TranslateService.GetTranslate("", "System_Add", "添加")
                        </button>
                    }
                    @if (candelete&&!isview)
                    {
                        <button onclick = "deleteData();" type = "button" class="btn btn-danger" aria-label="Right Align">
                            <span class="iconfont icon-ysic_delete" aria-hidden="true"></span>
                            @TranslateService.GetTranslate("", "System_Delete", "删除")
                        </button>

                    }
                        <button type = "button" class="btn btn-refresh" aria-label="Right Align" onclick="javascript: location.reload();">
                            <span class="iconfont icon-ysic_refresh" aria-hidden="true"></span>
                            @TranslateService.GetTranslate("", "System_Flash", "刷新")
                        </button>
                    </div>
                </form>
        </div>
    </div>
</div>
    <div class="fx-wrapper">
        <table id="dataTable" class="table-bordered"></table>
    </div>
@{
    var str = "";
    if (obj.Rows.Count>0)
    {
        str = "var json = { rows:JSON.parse('"+@Html.Raw(JsonConvert.SerializeObject(obj))+"')};sessionStorage.setItem('ms_messageuser'+guid,JSON.stringify(json))";
    }
    else {
        str = "var theEntity = sessionStorage.getItem('ms_messageuser'+guid);var json=JSON.parse(theEntity)";
    }
}
@{
    var ExFields = "";
    List<base_extendedfield> exfs = dataHelper.GetExFileds("PushMessage", "ms_messageuser");
    @foreach (var ex in exfs)
    {
        var name = TranslateService.GetTranslate("", $@"PushMessage_ms_messageuser_{ex.exfiled}", $@"{ex.filedname}");
        ExFields+=$@"{{ title: '{name}', field: '{ex.exfiled}', width: '5%' }},";
    }
}
<script>
    var isview=@isview.ToString().ToLower();
    var key ='@key';
    var value ='@value';
    var $table = $('#dataTable');
    var guid='@guid';
    @Html.Raw(str)
    $(function () {
        initTable();
        bindEvent();
        if(isview)
        {
            $(".column").attr("disabled",true);
        }
    });

    //初始化表格
    function initTable() {
        $table.bootstrapTable({
            data: json != null ? json.rows : [],
            idField: 'Id',
            clickToSelect: false,
            pagination: true,
            pageNumber: 1,
            pageSize: 30,
            pageList: [10, 30, 60, 100],
            showRefresh: true,
            showColumns: true,
            showToggle: true,
            onDblClickRow:function (row,$element,field) {
                if(field!='_')
                openForm(row['Id'],'@TranslateService.GetTranslate("","System_ViewData","查看数据")');
            },
            columns: [
                { title: 'ck', field: 'ck', checkbox: true, width: '3%' },
                {
                    title: '操作', field: '_', width: '80%', formatter: function (value,row, index) {
                        var builder = new BtnBuilder();
                        if(!isview){
                        //修改
                            builder.AddBtn({ name:'@TranslateService.GetTranslate("","System_Edit","修改")',icon: 'glyphicon-edit',type:'warning', function: 'openForm', param: [index] });
                        //删除
                            builder.AddBtn({ name:'@TranslateService.GetTranslate("","System_Delete","删除")',icon: 'glyphicon-trash',type:'danger', function: 'deleteData', param: [index] });
                        }
                        return builder.build();
                    }
                },
                 
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_userId","用户Id")', field: 'userId', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_userOpenId","用户OpenId")', field: 'userOpenId', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_serviceAppId","服务AppId")', field: 'serviceAppId', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_FsNo","排序")', field: 'FsNo', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_Remark","描述")', field: 'Remark', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_CreateDate","创建日期")', field: 'CreateDate', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_CreateOperator","创建人")', field: 'CreateOperator', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_ModifyDate","修改日期")', field: 'ModifyDate', width: '5%' },
                { title: '@TranslateService.GetTranslate("","PushMessage_ms_messageuser_ModifyOperator","修改人")', field: 'ModifyOperator', width: '5%' },     
                 @Html.Raw(ExFields)
                 {title: '使用状态', formatter: function (value, row, index) {
                        if (row.StatusFlag == '1') {
                            return '<span class="badge badge-primary">@TranslateService.GetTranslate("","System_Approve_Flag","已审核")</span>';
                        } if (row.StatusFlag == '2') {
                                return '<span class="badge badge-primary">@TranslateService.GetTranslate("","System_Reverse_Flag","反审核")</span>';
                        }if (row.StatusFlag == '0') {
                                return '<span class="badge badge-primary">@TranslateService.GetTranslate("","System_UnApprove_Flag","未审核")</span>';
                        }  
                    }}
            ],onPreBody: function (data) {
                for(var i=0,l=data.length;i<l;i++){
                    for(var key in data[i]){
                        if (data[i][key + "__Name"] != null) {
                            data[i][key] = data[i][key + "__Name"];
                        }
                    }
                }
            },
            queryParams: function (params) {
                return params;
            },
            onLoadSuccess: function () {
            },
            onLoadError: function () {
                showTips("数据加载失败！");
            }
        });
    }
    <!--hhs 2019-12-26 begin-->
    function UpladFile(fileObj) {
        loading();
        var form = new FormData(); // FormData 对象
        form.append("file", fileObj); // 文件对象
        $.ajax({
                url: '/PushMessage/ms_messageuser/ExportData',     //url地址
            type: 'POST',                 //上传方式
            data: form,                   // 上传formdata封装的数据
            dataType: 'JSON',
            cache: false,                  // 不缓存
            processData: false,        // jQuery不要去处理发送的数据
            contentType: false,         // jQuery不要去设置Content-Type请求头
            success: function(data) {          //成功回调
                //$table.bootstrapTable('refresh');
                //console.log(data);
                  loading(false);
                  if (data.Success) {
                    $table.bootstrapTable('refresh');
                        dialogSuccess('导入成功!');
                    }
                    else {
                        dialogError(data.Msg);
                    }
                       },
            error: function(data) {           //失败回调
                        loading(false);
                        dialogError(data.Msg);
                    }
            });
   }

    function upload() {
        $("#file").click();
   
    }
    <!--hhs 2019-12-26 end-->
    //绑定事件
    function bindEvent() {
        $('#file').change(function (e) {
            var fileName = e.target.files[0];//js 获取文件对象
            if (fileName !== undefined) {
                var file_typename = fileName.name.substring(fileName.name.lastIndexOf('.'));
                if (file_typename === '.xlsx' || file_typename === '.xls') {
                    $('#file').val('');
                    UpladFile(fileName);
                } else {
                    $('#file').val('');
                    console.log('@TranslateService.GetTranslate("","System_SelectErrorFile","请选择正确的文件类型！")')
                }
            } else {
                $('#file').val('');
                console.log('@TranslateService.GetTranslate("","System_SelectErrorFile","请选择正确的文件类型！")')
            }
        });
    }
      function down() {
         var condition = $("#condition").val();
         var keyword = $("#keyword").val();
         var searchParams = [];
         if (condition != '' && condition != null && keyword != '' && keyword!=null) {
             var searchinfo = new SearchInfo();
             searchinfo.FiledName = condition;
             searchinfo.Value = keyword;
             searchParams.push(searchinfo);
         }
         var values = $('#searchForm').getValues();
         for (var item in values) {
             if (item == 'condition' || item == 'keyword' || values[item] == '' || values[item] == null) continue;
             var Operate = $('#searchForm').find('#' + item).attr('Operate');
             if (Operate == null) Operate = '包含';
             var searchinfo = new SearchInfo();
             searchinfo.FiledName = item;
             searchinfo.Value = values[item].toString();
             searchinfo.Operate = Operate;
             searchParams.push(searchinfo);
         }
             var ids = [];

                var rows = $table.bootstrapTable('getSelections');
                if (rows.length == 0) {
                } else {
                    $.each(rows, function (index, value) {
                        ids.push(value['Id']);
                    })
                }
         postExcelFile({ searchInfos: searchParams, idlist: ids },'/PushMessage/ms_messageuser/ExportExcelBySearchInfo');
    }
    // 导出excel
        // 导出excel
    function postExcelFile(params, url) {
        //params是post请求需要的参数，url是请求url地址
        var form = document.createElement("form");
        form.style.display = "none";
        form.action = url;
        form.method = "post";
        form.enctype = "application/json";
        form.target = "iframe";
      document.body.appendChild(form);
    // 动态创建input并给value赋值
      for (var key in params) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = JSON.stringify(params[key]);
        form.appendChild(input);
      }

      form.submit();
      form.remove();
    }
    
    function getbtn(isview) { if (isview) return []; return ['@TranslateService.GetTranslate("","System_Confirm","确定")', '@TranslateService.GetTranslate("","System_Cancel","取消")'] };
    //打开表单
    function openFormView(id, title) {
    if(isview==null) isview=false;
        dialogOpen({
            id: 'form',
            title: title,
            btn: getbtn(isview),
            height:'80%',
            url: '/PushMessage/ms_messageuser/Form?id={0}'.format(id || '')+'&isview='+isview,
            yes: function (window, body) {
                if(!isview)
                window.submitForm();
                else
                window.clearForm();
            },
            no: function (window, body) {
                window.clearForm();
            }
        });  
    }
    
    //打开表单
    function openForm(index, title) {
        if(isview){
            openFormView(index, title);
        }else{
        dialogOpen({
            id: 'form',
            title: title,
            btn: ['@TranslateService.GetTranslate("","System_Confirm","确定")', '@TranslateService.GetTranslate("","System_Cancel","取消")'],
            height:'80%',
            url: ('/PushMessage/ms_messageuser/FormMain?rownum={0}&guid='+guid+'&key='+key+'&value='+value).format(index || ''),
            yes: function (window, body) {
                 window.submitForm();
                var data= sessionStorage.getItem("ms_messageuser"+guid);
                var json = JSON.parse(data)
                if (json != null)
                 { 
                    $table.bootstrapTable('load',json.rows);
                    $table.bootstrapTable('refresh');
                 }
            }
        });  
        }
    }

 

    //删除数据
    function deleteData(id) {
        dialogComfirm('@TranslateService.GetTranslate("","System_SureDelete","确认删除吗？")', function () {
            loading();
            var ids = [];
            var theEntity = sessionStorage.getItem("ms_messageuser"+guid);
            var json = JSON.parse(theEntity)
            if (typeof (id) == 'string') {//单条数据
                ids.push(id);
                json.rows.splice(id, 1);
                sessionStorage.setItem("ms_messageuser"+guid, JSON.stringify(json));
                $table.bootstrapTable('load', json.rows);
                $table.bootstrapTable('refresh');
                dialogSuccess('@TranslateService.GetTranslate("","System_DeleteSuccess","删除成功！")');
            } else {//多条数据
                var rows = $table.bootstrapTable('getSelections');
                if (rows.length == 0) {
                    dialogError('@TranslateService.GetTranslate("","System_NoSelectDeleteData","请选择需要删除的数据！")');
                    return;
                } else {
                    $.each(rows, function (index, value) {
                        json.rows.splice(index, 1);
                    })
                    sessionStorage.setItem("ms_messageuser"+guid, JSON.stringify(json));
                    $table.bootstrapTable('load', json.rows);
                    $table.bootstrapTable('refresh');
                    dialogSuccess('@TranslateService.GetTranslate("","System_DeleteSuccess","删除成功！")');
                }
            }

            loading(false);
        });
    }

    //审核数据
    function approveData(id) {
        dialogComfirm('@TranslateService.GetTranslate("","System_SureApprove","确认审核吗？")', function () {
            var ids = [];

            if (typeof (id) == 'string') {//单条数据
                ids.push(id);
            } else {//多条数据
                var rows = $table.bootstrapTable('getSelections');
                if (rows.length == 0) {
                    dialogError('@TranslateService.GetTranslate("","System_NoSelectApproveData","请选择需要审核的数据！")');
                    return;
                } else {
                    $.each(rows, function (index, value) {
                        ids.push(value['Id']);
                    })
                }
            }

            loading();
            $.postJSON('/PushMessage/ms_messageuser/ApproveData', { ids: JSON.stringify(ids) }, function (resJson) {
                loading(false);

                if (resJson.Success) {
                    $table.bootstrapTable('refresh');
                    dialogSuccess('@TranslateService.GetTranslate("","System_ApproveSuccess","审核成功！")');
                }
                else {
                    dialogError(resJson.Msg);
                }
            });
        });
    }

    //反审核数据
    function ReverseData(id) {
        dialogComfirm('@TranslateService.GetTranslate("","System_SureReverse","确认反审核吗？")', function () {
            var ids = [];

            if (typeof (id) == 'string') {//单条数据
                ids.push(id);
            } else {//多条数据
                var rows = $table.bootstrapTable('getSelections');
                if (rows.length == 0) {
                    dialogError('@TranslateService.GetTranslate("","System_NoSelectReverseData","请选择需要反审核的数据！")');
                    return;
                } else {
                    $.each(rows, function (index, value) {
                        ids.push(value['Id']);
                    })
                }
            }

            loading();
            $.postJSON('/PushMessage/ms_messageuser/ReverseData', { ids: JSON.stringify(ids) }, function (resJson) {
                loading(false);

                if (resJson.Success) {
                    $table.bootstrapTable('refresh');
                    dialogSuccess('@TranslateService.GetTranslate("","System_ReverseSuccess","反审核成功！")');
                }
                else {
                    dialogError(resJson.Msg);
                }
            });
        });
    }
</script>
